const router = require('koa-router')()
const uploader = require('../uploader')
const mongoose = require('mongoose')
const path = require('path')
const fs = require('fs')
const util = require('util')
const stats = require('../helpers/stats')
const rename = util.promisify(fs.rename)
const unlink = util.promisify(fs.unlink)
const popular = require('../helpers/images')
const newestComments = require('../helpers/comments')
router.prefix('/images')

const Image = mongoose.model('Image')
const Comment = mongoose.model('Comment')

router.post('/', uploader.single('file'), async function (ctx, next) {
  let file = ctx.req.file
  let diskFilename = file.filename + path.extname(file.originalname)
  await rename(file.path, path.dirname(file.path) + '/' + diskFilename)
      .then(() => Image.create({
          title: ctx.req.body.title,
          description: ctx.req.body.description,
          filename: diskFilename,
          mimetype: ctx.req.file.mimetype,
          originalname: ctx.req.file.originalname
      }))
      .then(doc => ctx.redirect(`/images/${doc.id}`))
      .catch(err => ctx.throw(500, err))
})

router.get('/:id', async ctx => {
  let image = await Image.findById(ctx.params.id)
  image.views = image.views + 1
  await image.save()
    await Promise.all([
              stats(),
              popular(),
              Comment.find({image: ctx.params.id}),
              newestComments()
    ])
    .then( ([stats, popular, comments, newestComments]) => ctx.render('image',
        {image, stats, popular, comments, newestComments}
    ))
    .catch(err => ctx.throw(500, err))
})

router.post('/like', async ctx => {
     await Image.findByIdAndUpdate(ctx.request.body.imageid, {$inc: {likes: 1}})
     .then(() => Image.findById(ctx.request.body.imageid))
     .then(doc => ctx.body = {likes: doc.likes})
     .catch(err => ctx.throw(500, err))

})
router.del('/:imageid', async ctx => {
    let image = await Image.findById(ctx.params.imageid)
    await unlink(path.resolve('./public/upload/' + image.filename))
   .then(() => Image.deleteOne({_id : ctx.params.imageid}))
   .then(() => Comment.deleteMany({image_id: ctx.params.imageid}))
   .then(() => ctx.body = { res: true })
   .catch(err => ctx.throw(500, err))
})

 router.post('/:imageid/comment', async ctx => {
     await Comment.create(Object.assign({}, ctx.request.body, {image_id: ctx.params.imageid}))
     .then(doc => ctx.redirect(`/images/${ctx.params.imageid}`))
     .catch(err => ctx.throw(500, err))
 })

 module.exports = router
